<template>
	<web-view v-if="src" :src="src" @message="webviewStore.onMessage"></web-view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed,
		nextTick
	} from 'vue'
	import {
		onLoad,
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		useAppStore
	} from '@/store/app'
	import {
		useWebviewStore
	} from '@/store/webview'
	import {
		useUserStore
	} from '@/store/user'
	import {
		queryStringToObject
	} from '@/common/common'
	import {
		dataSerialize
	} from "@/utils/md5/index.js"
	
	import {  getCurrentInstance } from 'vue';
	const CurrentInstance = getCurrentInstance()
	if (CurrentInstance) {
		// #ifdef MP-WEIXIN
		CurrentInstance.ctx.$scope.onShareAppMessage = () => {
			const shareData = webviewStore.share
			console.log(shareData, 'webview分享参数')
			return shareData
		};
		// #endif
	}
	
	const appStore = useAppStore()
	const webviewStore = useWebviewStore()
	const userStore = useUserStore()
	const src = ref('')

	onMounted(() => {
		appStore.loadingHandler(false)
		// #ifdef H5
		window.addEventListener('message', webviewStore.onH5Message, false);
		// #endif
	})
	onLoad((options)=>{
		
		console.log(options,'options')
		if(options.url){
			
			let url = decodeURIComponent(options.url)
			let path = decodeURIComponent(options.path)
			let route = path.split('?')[0] //提取页面路径
			let params
			//判断是否有带参数
			if(path.includes('?')){
				params = queryStringToObject('?' + path.split('?')[1]) //转成对象形式
			}else{
				params = {}
			}
			// 重新赋值该用户自身的信息
			params.user_id = userStore.user_id
			params.login_code = userStore.login_code
			params.open_id = userStore.open_id
			params.province = userStore.user_province
			params.isWebview = 1
			
			path = route + `?` + dataSerialize(params).slice(0, -1) //重新组合成字符串格式参数
			
			src.value = url + path
			
			console.log(url,'src.url')
			console.log(path,'src.path')
			console.log(src.value,'src.value1')
		}else{
			src.value = webviewStore.url + webviewStore.page + webviewStore.params
				+`&user_id=${userStore.user_id}`
				+`&login_code=${userStore.login_code}`
				+`&open_id=${userStore.open_id}`
				+`&province=${userStore.user_province}`
				
				console.log(src.value,'src.value2')
		}
		// #ifdef MP-WEIXIN
		wx.onCopyUrl(() => {
			console.log('复制链接分享触发')
			console.log(webviewStore.url,'复制链接分享触发')
			console.log(webviewStore.sharePath,'复制链接分享触发')
			return { query: `url=${encodeURIComponent(webviewStore.url)}&path=${encodeURIComponent(webviewStore.sharePath)}` }
		})
		// #endif
	})
	onShow(() => {

	})
	
	onUnmounted(()=>{
		// #ifdef H5
		// 移除事件监听器
		window.removeEventListener('message', webviewStore.onH5Message, false)
		// #endif
		// #ifdef MP-WEIXIN
		// 取消绑定分享参数
		wx.offCopyUrl()
		// #endif
	})
</script>

<style>
</style>